package top.cardone.security.shiro.func;

import lombok.Setter;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import top.cardone.core.util.func.Func1;

import java.util.Map;
import java.util.Objects;

/**
 * Created by cardone-home-001 on 2016/4/19.
 */
public class AuthorityFunc implements Func1<Boolean, Map<String, Object>> {
    @Setter
    String superPrincipal = "admin";
    @Setter
    private String permittedKeyName = "code";
    @Setter
    private String roleKeyName = "roleCode";

    @Override
    public Boolean func(Map<String, Object> params) {
        if (Objects.equals(superPrincipal, SecurityUtils.getSubject().getPrincipal())) {
            return true;
        }

        String role = MapUtils.getString(params, roleKeyName);

        if (StringUtils.isNotBlank(role)) {
            if (SecurityUtils.getSubject().hasRole(role)) {
                return true;
            }
        }

        String permitted = MapUtils.getString(params, permittedKeyName);

        if (StringUtils.isNotBlank(permitted)) {
            return SecurityUtils.getSubject().isPermitted(permitted);
        }

        return false;
    }
}